import { RegionOptions } from '../declare/type';
import { isString, isNumber } from '../utils/is';

export default class ICanvas {
  private rgb = [0, 0, 0];

  protected regions: RegionOptions[] = [];

  protected canvas: HTMLCanvasElement;

  protected canvasCcache: HTMLCanvasElement;

  protected ctx2d: CanvasRenderingContext2D;

  protected ctx2dCache: CanvasRenderingContext2D;

  protected width: number;

  protected height: number;

  constructor (width: number, height: number) {
    this.width = width;
    this.height = height;
    this.canvas = document.createElement('canvas');
    this.canvasCcache = document.createElement('canvas');
    const ctx2d = this.canvas.getContext('2d');
    const ctx2dCache = this.canvasCcache.getContext('2d');
    if (!ctx2d || !ctx2dCache) {
      throw new Error('未找到画布上下文');
    }
    this.ctx2d = ctx2d;
    this.ctx2dCache = ctx2dCache;
  }

  protected setCanvasSize (width?: number, height?: number) {
    if (width !== undefined) this.width = width;
    if (height !== undefined) this.height = height;
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    this.canvasCcache.width = this.width;
    this.canvasCcache.height = this.height;
  }

  public addHitRegion (region: RegionOptions) {
    this.regions.push(region);
  }

  public removeHitRegion (id: string | number) {
    if (isNumber(id)) {
      this.regions.splice(<number>id, 1);
    }
    if (isString(id)) {
      this.regions = this.regions.filter((region) => region.id !== id);
    }
  }

  public clearHitRegions () {
    this.regions = [];
  }

  public getContext2d (isCache: boolean = false) : CanvasRenderingContext2D {
    return isCache ? this.ctx2dCache : this.ctx2d;
  }

  public getCanvas (isCache: boolean = false) : HTMLCanvasElement {
    return isCache ? this.canvasCcache : this.canvas;
  }

  protected createRegionId () : string {
    let [r, g, b] = this.rgb;
    const ids = [r, g, b];
    if (r > 255) {
      throw new Error('无可用id');
    }
    b += 1;
    if (b > 255) {
      b = 0;
      g += 1;
      if (g > 255) {
        r += 1;
        g = 0;
      }
    }
    this.rgb = [r, g, b];
    return ids.join(',');
  }
}
